package com.hngy.xpq.viewflipperdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewFlipper;

public class MainActivity extends AppCompatActivity {

    private ViewFlipper advertise;
    private Animation[] animations = new Animation[2];
    final int FLAG = 0x001;
    private Message message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化
        init();
    }

    private void init() {
        advertise = findViewById(R.id.advertise);
        int[] advertises = getAdvertiseImages();
        // 广告瀑布
        AdvertiseFlipper(advertises);
    }

    private void AdvertiseFlipper(int[] images) {
        for (int i = 0 ; i < images.length ; i++){
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(images[i]);
            advertise.addView(imageView);
        }
        animations[0] = AnimationUtils.loadAnimation(this, R.anim.slide_in_right);
        animations[1] = AnimationUtils.loadAnimation(this, R.anim.slide_out_left);
        advertise.setInAnimation(animations[0]);     //广告进入画面
        advertise.setOutAnimation(animations[1]);    //广告退出画面
        message = Message.obtain();     //获得对象
        message.what = FLAG;            //设置消息代码
        handler.sendMessage(message);   //发送
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == FLAG){
                advertise.showPrevious();
            }
            message = handler.obtainMessage(FLAG);
            handler.sendMessageDelayed(message,3000);    //设置3秒延迟
        }
    };

    /**
     * 此处应为后端接收的广告数据
     * @return
     */
    private int[] getAdvertiseImages() {
        return new int[]
                {R.drawable.comm_one,R.drawable.comm_two,R.drawable.coom_three,R.drawable.coom_fove};
    }
}